var examId;


String.prototype.cut = function(n) {
	var length = this.length;
	var last = length <= n ? length : n;
	
	return this.substring(0, last-1 );
};


/**
 * 时间转化格式
 * 
 * @param s
 */
function turnDate(s) {
	var date = new Date(parseInt(s));
	return date.format("yyyy-MM-dd hh:mm");
}

// 获取当前的ID
$(document).ready(
		function() {
			var url = window.location.href;
			examId = parseInt(url.split("=")[1]);
			
			var colNames = ['','姓名','用户ID','时间','详情'];

			/**
			 * colModel 显示列的属性
			 *
			 * @type {Object}
			 */
			var colModel = [
				{ name:'first', index:'first', width:"50%", align:"left", title:false }, 	
				{ name:'username',index:'username', hidden:false,align:"center",formatter:function(cellvalue,options,rowObj){
					return "<a href='../user/other.html?otherId="+rowObj.id+"' title='查看TA的个人主页' target='_blank' >"+rowObj.username+"</a>";
				} },  
				{ name:'userId',index:'userId', hidden:true }, 
				{ name:'createtime',index:'createtime',align:"center",	formatter :function(cellvalue, options, rowObj) {
					return turnDate(rowObj.createtime);}, hidden:false },
				{ name:'id',index:'id',hidden:false,align:"center"},
			];

			/**
			 * rowNum 想要显示的数据行数
			 *
			 * @type {Number}
			 */

			var rowNum = 10;//测试翻页

			/**
			 * total_last 用于判定表格的总页码是否发生了改变
			 *
			 * @type {Number}
			 */

			var total_last = 0;

			/**
			 * loadDataSuccess 判定是否成功加载完数据
			 *
			 * @type {Boolean}
			 */

			var loadDataSuccess = false;


			$( "#answer-all" ).jqGrid({

				url: '../answer/allData.html?examId='+examId,
				datatype:"json",
				mtype: "POST",
				height: "auto",
				autowidth: true,
				colNames: colNames, 
				colModel: colModel,
				rowNum: rowNum, 
				viewrecords: true,
				emptyrecords : '暂时无人提交',
				pager: 'answer-all-pager', 
				jsonReader: {
					root: "result",
					page: "page",
					total: "total",
					records: "records",
					repeatitems: false,
					cell: "cell",
					id: "id"
				},
				
				gridComplete:function() {
					// 取消外边框
					$( "#gbox_releasedOf" ).css( "border", "none" );
					
					// 隐藏表头
					$( "#gview_releasedOf .ui-jqgrid-hdiv" ).css( "display", "none" );
					
					// 取消列间的分界限
					$( "#gview_releasedOf .ui-jqgrid-bdiv td" ).css( "border-right-style", "none" );

					// 改变底边框样式
					$( "#gview_releasedOf .ui-jqgrid-bdiv tr:not(:first-child) td" ).css( "border-bottom", "1px solid #E5E5E5" );
					
					// 取消最后一行的底边框
					$( "#gview_releasedOf .ui-jqgrid-bdiv tr td" ).css( "border-bottom-style", "none" );
					
					// 设置表格行高
					//$( "#gview_releasedOf .ui-jqgrid-bdiv tr:gt(0)" ).css( "height", "110px" );

					/**
					 * records 得到总记录数
					 *
					 * @type {Number}
					 */

			        var records =  $( "#answer-all" ).getGridParam( "records");
					
			        /**
					 * total 采用向上取整，计算出总页数
					 *
					 * @type {Number}
					 */

			        var total = Math.ceil(records/rowNum);
			        //console.info(records+" "+rowNum);
			        $( "#sp_1_answer-all-pager" ).text( total ); 
					/**
					 * IDs 获取当前页所有数据的id
					 *
					 * @type {Object}
					 */

					var IDs = $( "#answer-all" ).jqGrid( "getDataIDs" );
					//没有数据
					if(IDs.length==0){
						$("#helpDetailpager_center").hide();
						//$(".ui-paging-info").css("text-align","left");
						$(".ui-paging-info").css("font-size","15px");
						$(".ui-jqgrid-view").css("height","60px");
					}
					
					
					for (var i=0; i < IDs.length; i++) {

						/**
						 * everyRowData 根据某一行数据的id获取该数据所有信息
						 *
						 * @type {Object}
						 */

						var everyRowData = $( "#answer-all" ).jqGrid( "getRowData", IDs[i] );
						
						// 信息自定义模块
						var metadata ='<p class="form-context">' +   					
								            '<img src="../images/index/form_icon1.png">' +
								            '<span class="span2"><a href="../answer/scanOneUser.html?answerId='+everyRowData.id+'&examId='+examId+'" target="_blank" title="点击查看详情">'+i+'</a></span>' +
										'</p>';
						var metadata_id='<p class="form-context">' +   					
											'<span class="span2"><a href="../answer/scanOneUser.html?answerId='+everyRowData.id+'&examId='+examId+'" target="_blank" title="点击查看详情">查看</a></span>' +
										'</p>';
						
						$( "#answer-all" ).jqGrid( 'setRowData', IDs[i], { first: metadata,id:metadata_id} );
						// 取消提示信息
						$( ".metadata" ).parent("td").attr("title","");
				
			        }		
				},
				onSelectRow: function(rowid) {}

			});

});



/**
 * 
 */
$(document).ready(function(){
	$.ajax({
		url : '../answer/getAllAnswerCells2.html?examId='+examId,
		type : 'post',
		dataType : 'json',
		contentType : "application/x-www-form-urlencoded;charset=utf-8",
		success : function(result) {
			if(result==null || result.length==0){
				$("#allAnswersAnalysis").html("暂无数据");
				$("#allAnswersRTAnalysis").html("暂无数据");
			}
			else{
				var rightArray = undefined;
				var wrongArray = undefined;
				var avRT = undefined;//平均反应时间
				
				//得到每一组answerCell
				for(var answerId in result){
					if(isNaN(answerId)){
						break;
					}
					
					var answerCells = result[answerId];
					//每组单元格的个数,每一张为项目简介，扣除
					var num = answerCells.length;
					//init
					if(rightArray==undefined){
						rightArray = new Array();
						wrongArray = new Array();
						avRT = new Array();
						for(var i=0;i<num;++i){
							rightArray[i] = 0;
							wrongArray[i] = 0;
							avRT[i] = 0;
						}
					}
					//每一个cell
					var index=0;
					for(var cellId in answerCells){
						if(isNaN(cellId)){
							break;
						}
						var answerCell = answerCells[cellId];
						//统计 正确 与错误 数
						var answerRight = answerCell["answerRight"];
						if(answerRight==1){
							rightArray[index]++;
						}
						else if(answerRight==0){
							wrongArray[index]++;
						}
						
						//平均时间
						var rt = answerCell["rt"];
						if(rt!="0"){
							var rts = rt.split("-");
							var allTime=0;
							for(var j=0;j<rts.length;j++){
								allTime += parseInt(rts[j]);
							}
							avRT[index] = parseInt(allTime/rts.length);
						}
						else{
							avRT[index]=0;
						}
						++index;
					}
				}
				
				//得到数组后，开始绘制 jqplot
				analyse(rightArray,wrongArray,avRT);
			}
		},

		error : function() {
			alert("连接服务器出错");
		}
	});
});


/**
 * jqplot
 */
function analyse(s1,s2,rt){
	if((s1!=undefined && s1.length>0) && (s2!=undefined && s2.length>0)){
		$.jqplot.config.enablePlugins = true;
	
		var ticks = new Array(s1.length);
		for(var i=0;i<s1.length;++i){
			ticks[i]="第"+(i+1)+"张";
		}
		/**
		 * 正确与错误
		 */
		plot1 = $.jqplot('allAnswersAnalysis', [s1,s2], {
			animate: !$.jqplot.use_excanvas,
			seriesColors:['#17BDB8', '#C7754C'],
			seriesDefaults: {
				renderer:$.jqplot.BarRenderer,
				pointLabels: { show: true}
			},
			legend: {
				show: true,
				location: 'ne',
				placement: 'inside',
				labels:['正确','错误']
			},
			axes: {
				xaxis: {
					renderer: $.jqplot.CategoryAxisRenderer,
					ticks: ticks
				}
			},
			highlighter: { show: false }
		});
	}
	else{
		$('#allAnswersAnalysis').html("<p>暂无数据</p>");
	}
  
	/**
     * 反应时间
     */
	if(rt!=undefined && rt.length>0){
	    plot2 = $.jqplot('allAnswersRTAnalysis', [rt], {
	    	animate: !$.jqplot.use_excanvas,
	    	seriesColors:['#99CC33'],
	        seriesDefaults: {
	            renderer:$.jqplot.BarRenderer,
	            pointLabels: { show: true}
	        },
	        legend: {
	            show: true,
	            location: 'ne',
	            placement: 'inside',
	            labels:['反应时间']
	        },
	        axes: {
	            xaxis: {
	                renderer: $.jqplot.CategoryAxisRenderer,
	                ticks: ticks
	            }
	        },
	        highlighter: { show: false }
	    });
	}
	else{
		$('#allAnswersRTAnalysis').html("<p>暂无数据</p>");
	}

};
